/*
 *
 *  Copyright (C) 2010 GSyC/LibreSoft, Universidad Rey Juan Carlos.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Raúl Román López <rroman@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.Content;


import java.sql.Time;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.LibreGeoSocial.App.R;

public class ContentCreation{
	
	public static final int DIALOG_RECORD_AUDIO = 10500;
	public static final int DIALOG_STOP_RECORD_AUDIO = 10501;
	
	public static final int MENU = 10500;
	public static final int MENU_PHOTO = 10501;
	public static final int MENU_AUDIO = 10502;
	
	private static com.LibreGeoSocial.App.Multimedia.AudioManager aManager;

	private Activity mActivity;
	
	private volatile Thread th;
	
	private String time_str = "00:00";
	
	public ContentCreation(Activity mActivity){
		this.mActivity = mActivity;
	}
	
		public void onCreateOptionsMenu(Menu menu){
		SubMenu sub = menu.addSubMenu(0, MENU, 0, "Create content")
			.setIcon(R.drawable.media_add);
		sub.add(0,MENU_PHOTO, 0, "Photo");
		sub.add(0,MENU_AUDIO, 0, "Audio");
	}
	
	public boolean onOptionsItemSelected (MenuItem item){
		switch(item.getItemId()){
			
		case MENU_PHOTO:
			
			Intent i = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
			mActivity.startActivity(i);
    		break; 
			
		case MENU_AUDIO:
			mActivity.showDialog(DIALOG_RECORD_AUDIO);
			break;
			
		default:
			return false;
		}
		return true;
	}
	
	public Dialog onCreateDialog(int id) {
		
		switch(id){
		case DIALOG_RECORD_AUDIO:
			aManager = new com.LibreGeoSocial.App.Multimedia.AudioManager(mActivity);
			
			LayoutInflater factory2 = LayoutInflater.from(mActivity);
			final View textEntryView2 = factory2.inflate(R.layout.single_name, null);
			
			final EditText title = (EditText) textEntryView2.findViewById (R.id.single_name_title);
			
	        return new AlertDialog.Builder(mActivity)	        
	        .setTitle("Recording Audio")
	        .setView(textEntryView2)
	        .setPositiveButton("Record", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	mActivity.removeDialog(DIALOG_RECORD_AUDIO);
	            	String name = title.getText().toString();
	            	if (name != "")
	            		doRecording (mActivity, name);
	            	else
	            		Toast.makeText(mActivity, "Wrong title!", Toast.LENGTH_SHORT).show();
	            }
	        })
	        .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {

	                /* User clicked cancel so do some stuff */
	            }
	        })
	        .create();
	        
		case DIALOG_STOP_RECORD_AUDIO:
			LayoutInflater factory = LayoutInflater.from(mActivity);
			final View textEntryView = factory.inflate(R.layout.record_audio, null);
			
			final TextView time = (TextView) textEntryView.findViewById (R.id.record_tv);
			final ProgressBar pb = (ProgressBar) textEntryView.findViewById (R.id.record_pb);
			pb.setMax(10000);
			
			final Handler mHandler = new Handler(){
				@Override
				public void handleMessage(Message msg) {
					if(th!=null){
						int progress = aManager.getMaxAmplitude();
						time.setText(time_str);
						if(progress > pb.getMax())
							progress = pb.getMax();
						pb.setProgress(progress);
					}
				}
			};
			
			th = new Thread(){
				public void run(){
					int counter = 0;
					long clock = 0;
					while(Thread.currentThread().equals(th)){
						try {
							Thread.sleep(250);
							counter += 250;
							if(counter >= 1000){
								counter = 0;
								clock ++;
							}
							time_str = calculateTime(clock);
							mHandler.sendEmptyMessage(0);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							Log.e("ContentCreation", "", e);
						}
					}
						
				}
			};
			
			th.start();
			
	        return new AlertDialog.Builder(mActivity)	        
	        .setTitle("Recording Audio")
	        .setCancelable(false)
	        .setView(textEntryView)
	        .setPositiveButton("Stop", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	th = null;
	            	aManager.stopRecording();
	            	mActivity.removeDialog(DIALOG_STOP_RECORD_AUDIO);
	            }
	        })
	        .create();
		}
		return null;
		
	}
	
	private String calculateTime(long time){
		Time tme = new Time( time * 1000);
		String minutes = Integer.toString(tme.getMinutes());
		if(tme.getMinutes() < 10)
			minutes = "0" + minutes;
		String seconds = Integer.toString(tme.getSeconds());
		if(tme.getSeconds() < 10)
			seconds = "0" + seconds;
		return minutes + ":" + seconds;
	}
	
	private void doRecording (Activity mActivity, String name){
		
		aManager.setName(name);
		aManager.startRecording();
		
		mActivity.showDialog(DIALOG_STOP_RECORD_AUDIO);
	}
	
}